package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Mr_Su
 * @version v1.0
 * @date 2022/6/27 17:03
 * @desciption
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 1.判断当前请求是否为登录请求,如果是则直接放行
        // 获取当前请求的url
        String path = request.getURI().getPath(); // login/in
        if (path.contains("/login")){
            // 直接放行
            return chain.filter(exchange);
        }

        // 2.判断token
        // 2.1 首先判断请求头中是否有token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); // 直接返回给浏览器
        }

        // 2.2 通过JWT判断token是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int status = AppJwtUtil.verifyToken(claims);
            if (status == -1 || status == 0){
                // token有效,获取当前token中用户id,将userId放入到请求头中转发到后端的微服务,放行
                Integer userId = claims.get("userId", Integer.class);
                String name = claims.get("name", String.class);
                request.mutate().header("userId",userId.toString());
                request.mutate().header("name",name);
                return chain.filter(exchange);
            }
        }catch (Exception e){
            // 记录错误日志
            log.error(e.getMessage());
        }

        // 其他情况(异常),统一返回401未授权
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
